package com.fintech.third.utils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;

import com.fintech.common.enums.RespStatus;
import com.fintech.common.util.ApiResponse;
import com.fintech.third.constant.ThirdMethodConstants;
import com.fintech.third.dao.MoxieTaskInfoMapper;
import com.fintech.third.model.DataLogQuery;
import com.fintech.third.model.MoxieTaskInfo;
import com.fintech.third.model.ThirdProperties;
import com.fintech.third.service.moxie.MoXieService;
import com.fintech.third.utils.SerialNumCreater;
import com.marvels.common.utils.MarvelsLogUtil;

import net.sf.json.JSONObject;

public class MoXieCarrierThread implements Runnable {

	private static final ThirdProperties thirdProperties = ThirdPropertiesInitUtil.getThirdProperties();

	private Map<String, String> map;

	private MoXieService MoXie = (MoXieService) ApplicationContextGet.getApplicationContext().getBean("freshMoXie");

//	private loanInfoIDragonService loanInfoIDragonService = (loanInfoIDragonService) ApplicationContextGet.getApplicationContext()
//			.getBean("loanInfoIDragonService");

	public Map<String, String> getMap() {
		return map;
	}

	public void setMap(Map<String, String> map) {
		this.map = map;
	}

	@Override
	public void run() {
		String taskId=map.get("task_id");
		String loanId=map.get("loanId");
		String mobile=map.get("mobile");
		if (Boolean.parseBoolean(thirdProperties.getIs_mx_new_programme_user())) {//启用新方法
			MoxieTaskInfoMapper moxieTaskInfoMapper=(MoxieTaskInfoMapper)ApplicationContextGet.getApplicationContext().getBean("moxieTaskInfoMapper");
			
		//	if(MoXie.searchCarrierStatus(loanId)==null){
				MarvelsLogUtil.getInstance().info("==================添加运营商任务信息开始,loanId" + loanId + ",任务taskId" + taskId+",mobile"+mobile);
				MoxieTaskInfo moxieTaskInfo=new MoxieTaskInfo();
				moxieTaskInfo.setCreatedBy("sys");
				moxieTaskInfo.setUpdatedBy("sys");
				moxieTaskInfo.setCreatedDate(new Date());
				moxieTaskInfo.setLoanId(loanId);
				moxieTaskInfo.setTaskId(taskId);
				moxieTaskInfo.setUpdatedDate(new Date());
				moxieTaskInfo.setMobile(mobile);
				moxieTaskInfo.setType("1");
				moxieTaskInfo.setResult("0");
				moxieTaskInfoMapper.insertMoxieTaskInfo(moxieTaskInfo);
				MarvelsLogUtil.getInstance().info("==================添加运营商任务信息结束,loanId" + loanId + ",任务taskId" + taskId+",mobile"+mobile+",开始修改添加运营商任务信息状态");
//				AcLoanApplyInfo loan = new AcLoanApplyInfo();
//				loan.setLoanId(loanId);
//				loan.setOperatorDataCollectResult("2");
//				loanInfoIDragonService.input(loan);
				MarvelsLogUtil.getInstance().info("==================>>>>>修改运营商数据采集状态请求开始,loanId" + loanId +",任务taskId" + taskId +",结果状态为" + "2");
				try{
				//	moxieTaskInfoMapper.updateCarrierStatus(loanId, "2");
//					AcLoanApplyInfo loan = new AcLoanApplyInfo();
//					loan.setLoanId(loanId);
//					loan.setOperatorDataCollectResult("2");
//					loanInfoIDragonService.input(loan);
				}catch(Exception e){
					e.printStackTrace();
					MarvelsLogUtil.getInstance().info("==================修改运营商数据采集状态请求异常,loanId" + loanId +",任务taskId" + taskId +"错误信息:"+e.getMessage());
				}
				MarvelsLogUtil.getInstance().info("==================修改运营商数据采集状态请求结束,loanId" + loanId +",任务taskId" + taskId +",结果状态为" + "2");
		//	}
			
			
		} else {
			
			MarvelsLogUtil.getInstance().info("=============>>>>运营商数据采集线程开始,loanId:" + loanId + ",taskId:" + map.get("task_id") + ",mobile"
					+ mobile);
			long pollEndTime = System.currentTimeMillis() + thirdProperties.getPolling_time(); // 轮询最多3分钟
			boolean a = false;
			boolean b = false;
			boolean c = false;
			String status = "";
			Map<String, String> dataMap = new HashMap<String, String>();
			String serial_num = SerialNumCreater.creater("MX", loanId);
			while (true) {
				ApiResponse apiResponse = new ApiResponse();
				dataMap.put("task_id", map.get("task_id"));
				apiResponse = MoXie.obtainUserMobileReport(dataMap, mobile, serial_num, loanId,
						ThirdMethodConstants.channel);
				if (RespStatus.SUCCESS.getCode() == apiResponse.getCode()) {
					// 插入数据日志表
					// dataLogQuery.setRequestTime(date);
					// dataLogQuery.setResponseCode(apiResponse.getCode());
					// dataLogQuery.setResponseTime(responseDate);
					// dataLogQuery.setSerialNum(serial_num);
					// dataLogQuery.setResponseDetail(apiResponse.getMsg());
					// dataLogQuery.setMethod(ThirdMethodConstants.MX0001);
					// dataLogAddMapper.dataLogInsert(dataLogQuery);
					//
					a = true;
					break;
				}

				try {
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (System.currentTimeMillis() > pollEndTime) {
					MarvelsLogUtil.getInstance().info("==================>>>>>运营商查询用户报告时间超时,loanId:" + loanId);
					break;
				}

			}

			long endTime = System.currentTimeMillis() + thirdProperties.getPolling_time(); // 轮询最多3分钟
			while (true) {
				DataLogQuery dataLogQuery = new DataLogQuery();
				ApiResponse apiResponse = new ApiResponse();
				apiResponse = MoXie.obtainAllDataDetails(mobile, map.get("task_id"), serial_num, loanId,
						ThirdMethodConstants.channel);
				if (RespStatus.SUCCESS.getCode() == apiResponse.getCode()) {
					// // 插入数据日志表
					// dataLogQuery.setRequestTime(date);
					// dataLogQuery.setResponseCode(apiResponse.getCode());
					// dataLogQuery.setResponseTime(responseDate);
					// dataLogQuery.setSerialNum(serial_num);
					// dataLogQuery.setResponseDetail(apiResponse.getMsg());
					// dataLogQuery.setMethod(ThirdMethodConstants.MX0002);
					// dataLogAddMapper.dataLogInsert(dataLogQuery);
					//
					b = true;
					break;
				}

				try {
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (System.currentTimeMillis() > endTime) {
					MarvelsLogUtil.getInstance().info("==================>>>>>获取运营商全部数据时间超时,loanId:" + loanId);
					break;
				}
			}

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("status", status);
			jsonObject.put("loanId", loanId);
			String string = "";
			long modifyStatusTime = System.currentTimeMillis() + thirdProperties.getPolling_time(); // 轮询最多3分钟
			// while (true) {
			// try {
			// MarvelsLogUtil.getInstance().info("================>>>>修改运营商数据采集状态请求参数:" +
			// jsonObject.toString());
			// string =
			// HttpUtil.httpPost(thirdProperties.getOperator_request_url(),
			// jsonObject.toString());
			// MarvelsLogUtil.getInstance().info("=============>>>>运营商数据采集线程结束" + ",返回结果" + string);
			// return;
			// } catch (Exception e) {
			// e.printStackTrace();
			// MarvelsLogUtil.getInstance().info("================>>>>修改运营商数据采集状态请求异常:" +
			// e.getMessage());
			// }
			// try {
			// Thread.sleep(3000);
			// } catch (InterruptedException e) {
			// // TODO Auto-generated catch block
			// e.printStackTrace();
			// }
			// if (System.currentTimeMillis() > modifyStatusTime) {
			// MarvelsLogUtil.getInstance().info("==================>>>>>获取运营商全部数据时间超时");
			// break;
			// }
			// }

			long v2Time = System.currentTimeMillis() + thirdProperties.getPolling_time(); // 轮询最多3分钟
			while (true) {
				ApiResponse apiResponse = new ApiResponse();
				dataMap.put("task_id", map.get("task_id"));
				Date date = new Date();
				apiResponse = MoXie.obtainUserMobileReportV2(dataMap, mobile, serial_num, loanId,
						ThirdMethodConstants.channel);
				Date responseDate = new Date();
				if (RespStatus.SUCCESS.getCode() == apiResponse.getCode()) {
					// 插入数据日志表
					// dataLogQuery.setRequestTime(date);
					// dataLogQuery.setResponseCode(apiResponse.getCode());
					// dataLogQuery.setResponseTime(responseDate);
					// dataLogQuery.setSerialNum(serial_num);
					// dataLogQuery.setResponseDetail(apiResponse.getMsg());
					// dataLogQuery.setMethod(ThirdMethodConstants.MX0001);
					// dataLogAddMapper.dataLogInsert(dataLogQuery);
					//
					c = true;
					break;
				}

				try {
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (System.currentTimeMillis() > v2Time) {
					MarvelsLogUtil.getInstance().info("==================>>>>>运营商查询用户报告时间超时v2,loanId:" + loanId);
					break;
				}

			}

			// result -1 认证失败 0 未认证 1 认证中 2认证成功
			if (a && b && c) {
				status = "2";
			} else {
				status = "-1";
			}

			MarvelsLogUtil.getInstance().info("==================>>>>>修改运营商数据采集状态请求开始,loanId" + loanId + ",结果状态为" + status);
//			AcLoanApplyInfo loan = new AcLoanApplyInfo();
//			loan.setLoanId(loanId);
//			loan.setOperatorDataCollectResult(status);
//			loanInfoIDragonService.input(loan);
		}

	}
}
